package com.edu.lxshpc.controller;

import cn.hutool.core.util.RandomUtil;

import com.edu.lxshpc.dto.UserDto;
import com.edu.lxshpc.pojo.User;
import com.edu.lxshpc.povo.UserVO;
import com.edu.lxshpc.service.UserService;
import com.edu.lxshpc.utils.Result;
import com.edu.lxshpc.utils.Utils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


import static com.edu.lxshpc.utils.RedisStatic.USER_REGISTER_CODE;


/**
 * 用户类接口
 * @author zgh
 * @date 2023/10/24
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户类接口")
@Slf4j
public class UserController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 用户注册
     *
     * @param userDto 参数
     * @return 返回注册信息
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册")
    public Result Register(@RequestBody UserDto userDto) {
        log.info(userDto.toString());
        String code = userDto.getCode();
        // 1、手机号为空
        boolean validate = Utils.validate(userDto.getUsername());
        if (!validate) {
            return Result.fail("手机号格式错误！");
        }
        //密码加密
        userDto.setPassword(passwordEncoder.encode(userDto.getPassword()));
        // 验证码校验
        if ("".equals(code) || code == null) {
            return Result.fail("验证码不为空");
        }
        return userService.insertUser(userDto, code);
    }


    /**
     * 发送验证码
     *
     * @param phone 必须 手机号
     * @return 返回业务成功信息
     */
    @Operation(summary = "发送验证码", description = "发送验证码")
    @GetMapping("/sendCode")
    @Parameter(name = "phone", required = true, description = "需要发送验证码的手机号")
    public Result SendCode(String phone) {
        //1、手机号为空，返货错误信息
        if ("".equals(phone) || phone == null) {
            return Result.fail("手机号不能为空");
        }
        //2、手机号不为空,正则校验
        boolean match = Utils.validate(phone);
        if (!match) {
            return Result.fail("手机号码格式错误");
        }
        //3、校验通过
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(USER_REGISTER_CODE + phone, code, 60 * 5, TimeUnit.SECONDS);
        return Result.success();
    }

    /**
     * 获取用户信息
     * @param userId 用户id
     * @return 返回用户信息
     */
    @GetMapping("/info")
    public Result getInfo(@RequestParam Long userId) {
        if (userId == null) {
            return Result.fail("用户id不能为空");
        }
        return userService.getUserById(userId);
    }

    /**
     * 更新用户信息
     * @param userVO 用户信息
     * @return 业务结果
     */
    @PutMapping("/info")
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    public Result updateInfo(@RequestBody(required = true) UserVO userVO) {
        if (userVO.getId() == null) {
            return Result.fail("用户id不能为空");
        }
        return userService.updateUserById(userVO);
    }

    /**
     * 更新用户密码
     * @param userDto 用户信息
     * @return 返回用户信息
     */
    @PutMapping("/password")
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    public Result updatePassword( @RequestBody UserDto userDto) {
        if (userDto.getId() == null) {
            return Result.fail("用户id不能为空");
        }
        return userService.updatePasswordById(userDto);
    }
}
